<?php
/**
 * 
 */
namespace Admin\Controller;

use Think\Controller;
use Think\Log;

class RecordsManageController extends BaseController
{
	
	
	
	/* 余额明细表 */
	public function accountRecords(){
		
		$this->display();
	}
	public function accountRecordsList(){
		$_listrows = I('request._listrows', '', 'trim');
		
		$_where['transaction_type'] = 1;
		
		$is_vip = I('request.is_vip',-1,'intval');
		if( $is_vip != -1){
			$_where['is_vip']=$is_vip;
		}
		
		$keywords = I('request.keywords','','trim');
		if(!empty($keywords)){
			$_where['user_name|mobile_phone']=array('like',"%{$keywords}%");
		}
		
		$start_time = I('request.start_time','','trim');
		$end_time = I('request.end_time','','trim');
		
		if(!empty($start_time)){
			$str.=' and reg_time >= '.strtotime($start_time." 00:00:01");
		}
		if(!empty($end_time)){
			$str.=' and reg_time <= '.strtotime($end_time." 23:59:59");
		}
		
		$str = ltrim(trim($str),'and');
		if(!empty($str)){
			$_where['_string']=$str;
		}
		
		$where_order['where'] = $_where;
		$where_order['order'] = ' last_transaction_time desc ';
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div";
		$where_order["field"]="user_id,user_name,mobile_phone,user_money,reg_time,last_transaction_time";

		$_datalist = $this->_getListsFromModel('users', $where_order);
		$this->assign('_datalist', $_datalist);
		$this->display();
	}
	
	
	/* 收款充值 */
	public function recharges(){
		$this->display();
	}
	public function rechargesList(){
		$_listrows = I('request._listrows', '', 'trim');
		
		$_where['transaction_type'] = 1;
		
		$gathering_way = I('request.gathering_way',0,'intval');
		if(!empty($gathering_way)){
			$_where['gathering_way']=$gathering_way;
		}
		$keywords = I('request.keywords','','trim');
		if(!empty($keywords)){
			$_where['user_name|mobile|gathering_man|bank_transaction_id']=array('like',"%{$keywords}%");
		}
		
		$where_order['where'] = $_where;
		$where_order['order'] = ' add_time desc ';
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div";
		// 		$where_order["field"]="js_suppliers.logo_img,js_suppliers.code,js_country.country_id,js_country.country_title,js_suppliers.suppliers_id,js_suppliers.suppliers_name,js_suppliers.remark,js_suppliers.address,js_suppliers.mobile,js_suppliers.linkman,js_suppliers.is_dismantle,js_suppliers.aliasname";
		// 		$where_order["join"]="inner join js_country  on js_suppliers.country_id=js_country.country_id";
		$_datalist = $this->_getListsFromModel('purchase_price_list', $where_order);
		$this->assign('_datalist', $_datalist);
		$this->display();
	}
	public function addRecharges(){
		if(IS_POST){
			$this->addRechargesPost();
			exit();
		}
		
		$this->display();
	}

	public function addRechargesPost(){
		
		$user_name = I('request.user_name','','trim');
		$users = M('users')->where(array('user_name'=>$user_name))->field('mobile_phone,user_id,user_money')->find();

		if(empty($users)){
			$this->error('输入的用户登录帐号不存在，请核对再试!');
			exit;
		}

		$money = I('request.money',0,'doubleval');
		
		$_POST['source_data_id']=0;
		$_POST['source_type']=1;
		$_POST['transaction_type']=1;
		$_POST['in_or_out']='in';
		$_POST['user_id']=$users['user_id'];
		$_POST['mobile']=$users['mobile_phone'];
		$_POST['add_time']=time();
		$_POST['gathering_way'] =2;   //充值类型，1：现金，2：转账
		$_POST['gathering_time'] = date("Y-m-d H:i:s",time());//最后操作时间
		$_POST['user_balance_details'] = $users['user_money']+$money;//用户当前余额
		
		$pl = M('purchase_price_list')->add($_POST);
		
		if( $pl ){
			
			$present_money_set = 
				M('present_money_set')
					->where(array(
							'status'=>1,
							'money_start'=>array('elt',$money),
							'money_end'=>array('egt',$money),
					))->order('money_start desc')->find();
			if( !empty($present_money_set) ){
				$reward_percent = $present_money_set['send_money']/$present_money_set['every_money'];
				$reward_money = $money*$reward_percent;
				
				$_POST['source_type']=3;
				$_POST['transaction_type']=3;
				$_POST['reference']='赠款充值';
				$_POST['remark']='赠款充值';
				$_POST['money']=$reward_money;
				$_POST['gathering_time'] = date("Y-m-d H:i:s",time());//最后操作时间
				$_POST['user_balance_details'] = $users['user_money']+$reward_money+$money;//用户当前余额
				M('purchase_price_list')->add($_POST);
				
				$money = $money+$reward_money;
			}
			//累加user_money
			M('users')->where(array('user_id'=>$users['user_id']))->setInc('user_money',$money);			
			
			
			$exe_scriptstr = "<script>
                    setTimeout(function(){
                    var win=    art.dialog.opener;
                                win._reload_currentpage_datalist('load_tb_div');
                                art.dialog.close();
                    },2000);
                   </script>";
			$this->success('操作成功'.$exe_scriptstr);
		}else{
			$this->error('操作失败');
		}
		
		
		exit;
	}
	public function ajaxGetUserInfo(){
		$user_name = I('request.user_name','','trim');
		
		$mobile = M('users')->where(array('user_name'=>$user_name))->getField('mobile_phone');
		if( empty($mobile) ){
			echo json_encode(array('status'=>0));
		}else{
			echo json_encode(array('status'=>1,'data'=>$mobile));
		}
		exit;	
	}
	
	/* 货款流水表 */
	public function incomesRecords(){
		$keywords = I('request.keywords','','trim');
		$this->assign('keywords', $keywords);
		$this->display();
	}
	public function incomesRecordsList(){
		$_listrows = I('request._listrows', '', 'trim');
        
		
		$gathering_way = I('request.gathering_way',0,'intval');
		if(!empty($gathering_way)){
			$_where['gathering_way']=$gathering_way;
		}
		$transaction_type = I('request.transaction_type',0,'intval');
		if(!empty($transaction_type)){
			$_where['transaction_type']=$transaction_type;
		}
		
		
		$keywords = I('request.keywords','','trim');
		if(!empty($keywords)){
			$_where['u.user_name|gathering_man|bank_transaction_id']=array('like',"%{$keywords}%");
		}
		
		$start_time = I('request.start_time','','trim');
		$end_time = I('request.end_time','','trim');
		$str='';
		if(!empty($start_time)){
			$str.=' and add_time >= '.strtotime($start_time." 00:00:01");
		}
		if(!empty($end_time)){
			$str.=' and add_time <= '.strtotime($end_time." 23:59:59");
		}
		
		$str = ltrim(trim($str),'and');
		if(!empty($str)){
			$_where['_string']=$str;
		}
		$where_order['where'] = $_where;
		$where_order['order'] = ' add_time desc ';
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div";
		$where_order["alias"]="a";
		$where_order["field"]="a.*,u.user_money,CASE WHEN a.money>0 THEN  a.money ELSE 0 END AS income ,CASE WHEN a.money>0 THEN 0 ELSE ABS(a.money) END AS expenditure"; 
        $where_order["join"]=array(" left join ".$this->dbprefix."users u  on a.user_id=u.user_id");

		$_datalist = $this->_getListsFromModel('purchase_price_list', $where_order);

		foreach ($_datalist['lists'] as $key => $value) {
			//判断时 （支出expenditure）还是（收入income） 总支出金额(total_expenditure)   总收入金额（total_income）;
	     	if($value['money'] > 0){ 
                $total_amount['total_income'] += $value['money'];
	     	}else{ 
	     		$total_amount['total_expenditure'] +=  abs($value['money']);
	     	}
		} 

		$this->assign('list',$total_amount);
		$this->assign('_datalist', $_datalist);
		$this->display();
	}
	/* 详情 */
	public function rechargeDetails(){
		$r_id = I('request.r_id',0,'intval');
		
		$r = M('purchase_price_list')->where(array('id'=>$r_id))->find();
		$this->assign('ppl',$r);
		$this->display();
		
	}















	//退款充值 异步列表数据 20160408 ================================
	public  function  ajax_refund_list(){

		$_listrows = I('request._listrows', '', 'trim');

		$_where['transaction_type'] = 5;

		$gathering_way = I('request.gathering_way',0,'intval');
		if(!empty($gathering_way)){
			$_where['gathering_way']=$gathering_way;
		}
		$keywords = I('request.keywords','','trim');
		if(!empty($keywords)){
			$_where['user_name|mobile|gathering_man|bank_transaction_id']=array('like',"%{$keywords}%");
		}

		$where_order['where'] = $_where;
		$where_order['order'] = ' add_time desc ';
		$where_order['listrows'] = $_listrows;
		$where_order["id"]="load_tb_div";
		// 		$where_order["field"]="js_suppliers.logo_img,js_suppliers.code,js_country.country_id,js_country.country_title,js_suppliers.suppliers_id,js_suppliers.suppliers_name,js_suppliers.remark,js_suppliers.address,js_suppliers.mobile,js_suppliers.linkman,js_suppliers.is_dismantle,js_suppliers.aliasname";
		// 		$where_order["join"]="inner join js_country  on js_suppliers.country_id=js_country.country_id";
		$_datalist = $this->_getListsFromModel('purchase_price_list', $where_order);
		$this->assign('_datalist', $_datalist);







		$this->display();

	}






    //添加退款充值
	public  function  refund(){

		$this->display();

	}


    
	//添加退款充值
	public  function  add_refund(){

		$this->display();

	}

    
	public function add_refundPost(){



		$user_id = I('user_id','','trim');
		$users = M('users')->where(array('user_id'=>$user_id))->field('mobile_phone,user_id,user_name,user_money')->find();
 
		$order_number= I("order_number");
		$entity = M('order_info')->field('user_id,order_status,order_amount')->where(array('order_sn'=>$order_number))->find();

		if(empty($entity)){
			$this->error('输入的用户订单编号不存在，请核对再试!');
			exit;
		}
        

		if(empty($users)){
			$this->error('用户登录帐号不存在，请核对订单编号再试!');
			exit;
		}


        
		if($entity['order_status'] != 2 ){
			$this->error('订单状态不是已取消状态，不能添加退款!');
			exit;
		}

        
		$money = I('request.money',0,'doubleval');



        /*
         * 流水记录来源类别：
         * 1：收款充值-来源为ki_purchase_price_list表
         * 2：下单购物-来源为ki_order_info表
         * 3：赠款充值-来源为ki_purchase_price_list表
         * 4：红冲-来源为ki_purchase_price_list表
         * 5：退款充值-来源为  ki_order_info 表
         * **/
        $_POST['source_type']=5;
		$_POST['source_data_id']=0;
		
		/*
             * 交易类型：
             * 1: 收款充值
             * 2: 买货扣除
             * 3: 赠款充值
             * 4: 红冲
             * 5: 退款充值
             **/
		$_POST['transaction_type']=5;
		$_POST['in_or_out']='IN';    //进账
		$_POST['order_sn']=I('order_number');
		$_POST['user_id']=$users['user_id'];
		$_POST['user_name']=$users['user_name'];
		$_POST['mobile']=$users['mobile_phone'];
		$_POST['add_time']=time();

		/*
         * 收款方式：
         * 1：现金
         * 2：转账
         * 3：退款充值
         * **/
		$_POST['gathering_way'] =3;  
		$_POST['user_balance_details'] = $users['user_money']+$money;//用户当前余额



		$pl = M('purchase_price_list')->add($_POST);

		if( $pl ){

			//累加user_money
			M('users')->where(array('user_id'=>$users['user_id']))->setInc('user_money',$money);


			$exe_scriptstr = "<script>
                    setTimeout(function(){
                    var win=    art.dialog.opener;
                                win._reload_currentpage_datalist('load_tb_div');
                                art.dialog.close();
                    },2000);
                   </script>";
			$this->success('操作成功'.$exe_scriptstr);
		}else{
			$this->error('操作失败');
		}


		exit;
	}







	
}